package com.bdqn.ch02.SZ.sz3;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;

/**
 * DOM4JAddUpdDelTest
 *
 * 使用DOM4J进行对文档的修改
 * @aurhor Administrator  whs
 * @since 2024/7/1
 */
public class DOM4JDeleteTest {

    public static void main(String[] args) throws IOException {

        Document doc = null;
        //加载DOM树
        SAXReader saxReader = new SAXReader();
        try {
            doc = saxReader.read(new File("src/com/bdqn/ch02/SZ/sz1/手机品牌.xml"));
            // 获取XML的根节点
            Element root = doc.getRootElement();

        // 使用 DOM4J 修改

            for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext(); ) {
                Element brandEle = iterator.next();
                Attribute attribute = brandEle.attribute("name");

                if (attribute != null && attribute.getValue().equals("iQOONOE5")){
                    brandEle.remove(attribute);
                    System.out.println("使用DOM4J删除成功！🐳");
                }
            }







        } catch (
                DocumentException e) {
            e.printStackTrace();
        } catch (
                MalformedURLException e) {
            e.printStackTrace();
        }
        XMLWriter writer = new XMLWriter(new FileWriter("src/com/bdqn/ch02/SZ/sz1/手机品牌.xml"), OutputFormat.createPrettyPrint());
        OutputFormat format= OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        writer.write(doc);
        writer.close();
    }
}
